package thread;

/**
 * Created with IDEA
 * author:ju bai
 * Date:2021/4/26
 * Time:20:30
 **/
public class ThreadDemo4 {
    //执行的循环次数
    public static final Long count = 5_0000_0000L;

    public static void main(String[] args) throws InterruptedException {
        //System.out.println(Thread.currentThread().getName());
        //调用多线程
        concurrency();
        //调用单线程
        serial();
    }

    private static void serial() {
        //开始时间
        Long stime = System.currentTimeMillis();
        int a = 0;
        for (int i = 0; i < 3 * count; i++) {
            a++;
        }
        //结束时间
        Long etime = System.currentTimeMillis();
        System.out.println("单线程执行了" + (etime - stime));
    }

    private static void concurrency() throws InterruptedException {
        //开始时间
        Long stime = System.currentTimeMillis();
        //执行30亿次循环
        //创建线程
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                //具体业务
                int a = 0;
                for (int i = 0; i < count; i++) {
                    a++;
                }
            }
        });
        //开始执行线程
        t1.start();
        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                int b = 0;
                for (int i = 0; i < count; i++) {
                    b++;
                }
            }
        });
        t2.start();
        //让主线程执行10亿次
        int c = 0;
        for (int i = 0; i < count; i++) {
            c++;
        }
        //等待t1 t2 执行完后，统计时间
        t1.join();
        t2.join();

        //结束时间
        Long etime = System.currentTimeMillis();
        System.out.println("多线程执行了" + (etime - stime));
    }
}
